package com.cyou.dream.rule;

import com.cyou.dream.application.ApplicationCommon;
import com.cyou.dream.context.RuleContext;
import com.cyou.dream.core.IRule;
import com.cyou.dream.define.ERule;
import com.cyou.dream.define.ERuleParam;
import com.cyou.dream.rule.param.MultiStepCounterParam;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collections;
import java.util.List;

/**
 * 自增计数器规则（一次可以加超过1的数）
 * <p>
 *     需要业务传入的值参数：
 *     <ul>
 *         <li> {@code ERuleParam.STEP} - 步长 </li>
 *     </ul>
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class MultiStepCounterRule implements IRule {

    @Override
    public boolean evaluate(RuleContext context) {

        MultiStepCounterParam valueParams = (MultiStepCounterParam) context.getValueParams();

        if(valueParams == null || valueParams.getStep() == null) {
            throw new IllegalArgumentException("MultiStepCounterRule need value params");
        }

        Object[] args = {
                context.getRuleParams().get(ERuleParam.THRESHOLD.getKey()),
                valueParams.getStep()
        };

        List<String> keys = Collections.singletonList(context.getActualKey());

        RedisTemplate redisTemplate = ApplicationCommon.context().getBean("redisTemplate", RedisTemplate.class);

        Long result = (Long) redisTemplate.execute(
                ERule.MULTI_STEP_COUNTER.getRuleScript(),
                keys,
                args
        );

        return result == 1;
    }
}
